using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Configuration;

public partial class OpenChooseProject : System.Web.UI.Page
{
    Data.VarParams varParam;

    public Data.DataConsolidation dc = null;
    public Data.Data currentData = null;
    LoginHelper lh = null; 

    protected void Page_Load(object sender, EventArgs e)
    {
        lh = new LoginHelper(this);

        String myDataDir = (String)Session["MyApplicationDirectory"];
        if (myDataDir == null)
        {
            myDataDir = Request.Params["a"];
            if (myDataDir == null)
                Response.Write(" Your session is expired or this page wasn't started correctly. Try starting it with ?a=windmill for our demo data.");
        }

        String myApplicationDir = Request.PhysicalApplicationPath + myDataDir;
        varParam = new Data.VarParams();
        String errMsg = varParam.ReadFile(myApplicationDir, this.Session.SessionID);
        if (errMsg != null)
        {
            form1.Visible = false;
            Response.Write(errMsg);
            return;
        }

        dc = new Data.DataConsolidation(varParam);
        currentData = new Data.Data();
        if (currentData == null)
            return;

        if (IsPostBack == false)
        {
            FilenameToSaveTo.Text = lh.GetProjectCaption();
            getProjects();
            handleSelectionChange();
        }
    }

    private void getProjects()
    {
        /* get the name of the projects subdirectory out of the varParam and then
        * go get a list of all the files in it and put that list into the the ArrayList */

        string subdir = varParam.GetMyProjectsDir();
        if (System.IO.Directory.Exists(subdir) == false)
            return;

        String[] unvalidatedFileNames = System.IO.Directory.GetFiles(subdir);

        ArrayList fileNames = new ArrayList();
        ArrayList externalNames = new ArrayList(); 

        for (int i = 0, count = unvalidatedFileNames.Length; i < count; i++)
        {
            string projectFile = (string)unvalidatedFileNames[i];
            string projectCaption = projectFile.Replace(subdir, "");

            if (projectCaption.StartsWith("_") == false)
            {
                fileNames.Add(projectCaption);
                externalNames.Add(projectCaption);
            }
        }
        // in the end, if there are no valid project files, then they will be valid ArrayList objects but with zero count

        SortedList listItems = new SortedList(fileNames.Count);
        for (int i = 0, count = fileNames.Count; i < count; i++)
        {
            ListItem li = new ListItem((string)externalNames[i], (string)fileNames[i]);
            listItems.Add(externalNames[i], li);
        }

        this.ProjectList.Items.Clear();
        for (int i = 0, count = listItems.Count; i < count; i++)
        {
            ListItem li = (ListItem)listItems.GetByIndex(i);
            this.ProjectList.Items.Add(li);

            if( FilenameToSaveTo.Text.Equals( li.Text, StringComparison.CurrentCultureIgnoreCase ))
                ProjectList.SelectedIndex = i;
        }


    }

    protected void DoOpenProject(object sender, EventArgs e)
    {
        if (ProjectList.SelectedIndex != -1)
        {
            string projectFileName = ProjectList.SelectedValue;

            Button btn = (Button)sender;
            string arg = btn.CommandArgument;

            if (arg.Equals("Quick", StringComparison.CurrentCultureIgnoreCase))
            {
                Response.Redirect(lh.RedirectInfo("OpenQuickView.aspx", projectFileName), true);
            }
            else if (arg.StartsWith("Log", StringComparison.CurrentCultureIgnoreCase))
            {
                Response.Redirect(lh.RedirectInfo("OpenLogin.aspx", ""), true);
            }
            else
            {
                lh.SetProjectCaption(projectFileName);
                Response.Redirect(lh.RedirectInfo("OpenAuthorMode.aspx", projectFileName), true);
            }
        }
    }

    protected void TestEnable(object sender, EventArgs e)
    {
        testEnable();
        handleSelectionChange();
    }

    private void testEnable()
    {
        ThisProject.Enabled = ProjectList.Items.Count > 0 && ProjectList.SelectedIndex != -1;

    }

    private void Repaint()
    {
        AllPagesArea.Controls.Clear();

        if (currentData == null)
            return;

        MakeHtmlTable.makeHTMLTable( true, AllPagesArea, 1000, currentData, varParam );
    }

    protected void ToExternalContentType(object sender, EventArgs e)
    {
        Button btn = (Button)sender;
        string arg = btn.CommandArgument;

        /* If we can't get it looking right, then perhaps the next best thing is to redirect to a dynamically generated page, i.e. not "this" page
         */

        Response.Clear();
        Response.ContentType = arg;

        ChooseProjectPanel.Visible = false;
        Repaint();
    }

    protected void HandleMenuItemClick(object sender, MenuEventArgs e)
    {
        string id = e.Item.Value;

        if (id.Equals("Author", StringComparison.CurrentCultureIgnoreCase))
        {
            string targetName = "OpenAuthorMode";
            Response.Redirect(lh.RedirectInfo(targetName + ".aspx", lh.GetProjectCaption()), true);
        }
        else if (id.Equals("ChooseProject", StringComparison.CurrentCultureIgnoreCase))
        {
            string targetName = "OpenChooseProject";
            Response.Redirect(lh.RedirectInfo(targetName + ".aspx", lh.GetProjectCaption()), true);
        }
        else if (id.StartsWith("application/", StringComparison.CurrentCultureIgnoreCase))
        {
            Response.Clear();
            ChooseProjectPanel.Visible = false;
            Response.ContentType = id;
        }

        Repaint();
    }

    private void handleSelectionChange()
    {
        string projectFileName = ProjectList.SelectedValue;
        lh.SetProjectCaption(projectFileName);

        if (DoProcessProject(IsPostBack))
        {
            FilenameToSaveTo.Text = lh.GetProjectCaption();
            Repaint();
        }
    }

    bool DoProcessProject(bool IsPostBack)
    {
        bool result = DoProject.ExecuteProjectFile(lh.GetProjectCaption(), varParam, dc, currentData, IsPostBack);
        return result;
    }


}
